#!/bin/bash

# ====== 配置区 ======
TS3_VERSION="3.13.7"
TS3_FILENAME="teamspeak3-server_linux_amd64-${TS3_VERSION}.tar.bz2"
TS3_URL_GLOBAL="https://files.teamspeak-services.com/releases/server/${TS3_VERSION}/${TS3_FILENAME}"
TS3_URL_CHINA="https://gitee.com/wanxaio/ts3_install/raw/master/${TS3_FILENAME}"
INSTALL_DIR="/opt/teamspeak3"
TS_USER="ts3"
SERVICE_FILE="/etc/systemd/system/ts3server.service"

# ====== 端口输入 ======
get_ports() {
    echo "📡 请输入 TeamSpeak 服务端口（按 Enter 使用默认值）"
    read -p "通信端口（默认9987 UDP）: " PORT_VOICE
    read -p "查询端口（默认10011 TCP）: " PORT_QUERY
    read -p "文件传输端口（默认30033 TCP）: " PORT_FILE

    PORT_VOICE=${PORT_VOICE:-9987}
    PORT_QUERY=${PORT_QUERY:-10011}
    PORT_FILE=${PORT_FILE:-30033}
}

# ====== 是否使用国内镜像 ======
select_download_url() {
    echo "🌐 是否在中国大陆地区安装？(Y/n)"
    read in_china
    if [[ "$in_china" == "y" || "$in_china" == "Y" || "$in_china" == "" ]]; then
        TS3_URL=$TS3_URL_CHINA
        echo "🇨🇳 使用 Gitee 镜像下载 TeamSpeak 安装包。"
    else
        TS3_URL=$TS3_URL_GLOBAL
        echo "🌍 使用官方国际源下载 TeamSpeak 安装包。"
    fi
}

# ====== 防火墙开放端口 ======
open_firewall_ports() {
    echo "🔓 正在开放防火墙端口..."
    if command -v ufw >/dev/null 2>&1; then
        ufw allow $PORT_VOICE/udp
        ufw allow $PORT_QUERY/tcp
        ufw allow $PORT_FILE/tcp
    elif command -v firewall-cmd >/dev/null 2>&1; then
        firewall-cmd --permanent --add-port=$PORT_VOICE/udp
        firewall-cmd --permanent --add-port=$PORT_QUERY/tcp
        firewall-cmd --permanent --add-port=$PORT_FILE/tcp
        firewall-cmd --reload
    else
        echo "⚠️ 未检测到 ufw/firewalld，可能需要手动开放端口。"
    fi
}

# ====== 安装 TeamSpeak ======
install_ts3() {
    get_ports
    select_download_url
    open_firewall_ports

    echo "🔧 正在安装 TeamSpeak3..."

    # 创建系统用户
    if ! id -u $TS_USER >/dev/null 2>&1; then
        useradd -r -s /bin/false $TS_USER
    fi
    apt update
    apt install bzip2 -y
    mkdir -p $INSTALL_DIR
    cd /tmp
    wget -q $TS3_URL
    tar -xjf $TS3_FILENAME
    mv teamspeak3-server_linux_amd64/* $INSTALL_DIR
    chown -R $TS_USER:$TS_USER $INSTALL_DIR

    # 创建配置文件
    cat > $INSTALL_DIR/ts3server.ini <<EOF
default_voice_port=$PORT_VOICE
filetransfer_port=$PORT_FILE
query_port=$PORT_QUERY
license_accepted=1
EOF

    # 创建 systemd 服务
    cat > $SERVICE_FILE <<EOF
[Unit]
Description=TeamSpeak 3 Server
After=network.target

[Service]
WorkingDirectory=$INSTALL_DIR
User=$TS_USER
Group=$TS_USER
Type=forking
ExecStart=$INSTALL_DIR/ts3server_startscript.sh start inifile=ts3server.ini
ExecStop=$INSTALL_DIR/ts3server_startscript.sh stop
PIDFile=$INSTALL_DIR/ts3server.pid
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

    chmod 644 $SERVICE_FILE
    systemctl daemon-reexec
    systemctl daemon-reload
    systemctl enable ts3server

    echo "🚀 正在启动服务器以生成管理员 Token..."
    systemctl start ts3server
    sleep 10
    show_token
}

# ====== 显示管理员 token ======
show_token() {
    TOKEN=$(grep -i "token=" $INSTALL_DIR/logs/ts3server_*.log | tail -1 | sed -n 's/.*token=\(.*\)/\1/p')
    if [ -n "$TOKEN" ]; then
        echo "🔑 管理员 Token: $TOKEN"
    else
        echo "⚠️ 未找到 Token，请确认服务正常运行。"
    fi
}

# ====== 卸载 ======
uninstall_ts3() {
    echo "⚠️ 即将卸载 TeamSpeak3 并删除所有数据，是否继续？(y/n)"
    read confirm
    if [[ "$confirm" != "y" ]]; then
        echo "❎ 取消卸载。"
        return
    fi

    systemctl stop ts3server
    systemctl disable ts3server
    rm -f $SERVICE_FILE
    systemctl daemon-reload

    rm -rf $INSTALL_DIR
    userdel -r $TS_USER 2>/dev/null

    echo "🧹 已成功卸载 TeamSpeak3。"
}

# ====== 管理菜单 ======
menu() {
    while true; do
        echo ""
        echo "========= TeamSpeak3 管理菜单 ========="
        echo "1) 安装 TeamSpeak3 服务端"
        echo "2) 启动服务器"
        echo "3) 停止服务器"
        echo "4) 重启服务器"
        echo "5) 查看状态"
        echo "6) 显示管理员 Token"
        echo "7) 卸载 TeamSpeak3"
        echo "8) 退出"
        read -p "请输入选项 [1-8]: " choice

        case $choice in
            1) install_ts3 ;;
            2) systemctl start ts3server && echo "✅ 已启动。" ;;
            3) systemctl stop ts3server && echo "🛑 已停止。" ;;
            4) systemctl restart ts3server && echo "🔄 已重启。" ;;
            5) systemctl status ts3server ;;
            6) show_token ;;
            7) uninstall_ts3 ;;
            8) echo "👋 再见！"; exit 0 ;;
            *) echo "❌ 无效选项，请重试。" ;;
        esac
    done
}

# ====== 启动菜单 ======
menu